var API = {

    getFirstMenu: function (callback) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.GENERAL_IPS[0].getMenus1_new,
            data: {
                loginToken: LOGIN_TOKEN
            },
            success: function (data) {
                console.log(data);
                callback(data);
            },
            dataType: 'json'
        })
    },
    getSecondMenu: function (pmenuid, pageIndex, pageSize, callback) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.GENERAL_IPS[0].getMenuByPid_new,
            data: {
                pmenuid: pmenuid,
                pageIndex: pageIndex || 0,
                pageSize: pageSize || 10,
                loginToken: LOGIN_TOKEN
            },
            success: function (data) {
                console.log(data);
                callback(data);
            },
            dataType: 'json'
        })
    },

    //登陆接口
    login: function (phoneNumber, password, userType, callback) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.GENERAL_IPS[0].phoneLogin,
            data: {
                businessId: CONFIG['businessId'],
                businessCode: CONFIG['businessCode'],
                platformCode: CONFIG['platformCode_tv_web'],
                versionCode: CONFIG['API_VERSION'],
                phoneNumber: phoneNumber,
                password: password,
                userType: userType
            },
            success: function (data) {
                console.log(data);
                callback(data);
            },
            dataType: 'json'
        })
    },
    MACLogin: function (macAddress, callback) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.GENERAL_IPS[0].macLogin,
            async: false,
            data: {
                businessId: CONFIG['businessId'],
                businessCode: CONFIG['businessCode'],
                platformCode: CONFIG['platformCode'],
                versionCode: CONFIG['API_VERSION'],
                macAddress: macAddress
            },
            success: function (data) {
                console.log(data);
                callback(data);
            },
            dataType: 'json'
        })
    },

    // 发送手机验证码
    sendMessage: function (phoneNum, resolve, reject) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.GENERAL_IPS[0].xHanNews_sendMessage_v1_0,
            data: {
                phoneNumber: phoneNum
            },
            dataType: 'json',
            success: function (res) {
                console.log(res);
                if (res.status) {
                    resolve && resolve(res);
                } else {
                    reject && reject(res.message);
                }
            },
            error: function () {
                reject && reject('服务器出错，请稍后再试');
            }
        });
    },

    // 短信验证
    validateCode: function (phoneNum, code, resolve, reject) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.GENERAL_IPS[0].xHanNews_validateCode_v1_0,
            data: {
                phoneNumber: phoneNum,
                code: code
            },
            dataType: 'json',
            success: function (res) {
                console.log('>>>>>' + res);
                if (res.status == "1") {
                    resolve && resolve(res);
                } else {
                    reject && reject(res.message);
                }
            },
            error: function () {
                reject && reject('服务器出错，请稍后再试');
            }
        });
    },

    // 找回密码
    findPwd: function (phoneNum, newPwd, uid, resolve, reject) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.HTTP + CONFIG.GENERAL_IPS[0].phoneFindePwd,
            data: {
                phoneNumber: phoneNum,
                password: newPwd,
                ubusinessId: uid
            },
            dataType: 'json',
            success: function (res) {
                console.log(res);
                if (res.status) {
                    resolve && resolve(res);
                } else {
                    reject && reject(res.message);
                }
            },
            error: function () {
                reject && reject('服务器出错，请稍后再试');
            }
        });
    },
    //获取用户信息
    getUserInfo: function (callback) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.VILLAGE_URLS[0].userFarmersInfoV10,
            data: {
                loginToken: LOGIN_TOKEN
            },
            success: function (data) {
                console.log(data);
                tools.setStore('user_name', data.datas_userUserealinfotb[0].realName);
                callback(data);
            },
            dataType: 'json'
        })
    },
    updateUserInfo: function (userId, sex, userealinfoId, headPortraitFilepath, success, defeat, error) {
        $.ajax({
            url: CONFIG.VILLAGE_URLS[0].userAddUpdateV10 + '&userId=' + userId + '&sex=' + sex + '&judge=picture' + '&userealinfoId=' + userealinfoId + '&loginToken=' + LOGIN_TOKEN,
            type: 'POST',
            data: {
                headPortraitFilepath: headPortraitFilepath,
            },
            success: function (data) {
                console.log(data);
                if (data.status === 1) {
                    success && success(data)
                } else {
                    defeat && defeat(data)
                }
            },
            error: function () {
                error && error();
            },
            dataType: 'json'
        })
    },
    // 获取banner置顶
    getTopNews: function (menuID, callback) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.VILLAGE_URLS[0].getLocalLawTopList,
            data: {
                menuId: menuID,
                pageIndex: 0,
                pageSize: 5,
                loginToken: LOGIN_TOKEN
            },
            success: function (data) {
                console.log(data);
                if (data.status) {
                    callback(data);
                }
            },
            dataType: 'json'
        })
    },
    // 获取消息通知
    getNotice: function (success, defeat, error) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.VILLAGE_URLS[0].culturaSouvenirUserPraise,
            data: {
                loginToken: LOGIN_TOKEN
            },
            success: function (data) {
                console.log(data);
                if (data.status === 1) {
                    success && success(data)
                } else {
                    defeat && defeat(data)
                }
            },
            error: function () {
                error && error();
            },
            dataType: 'json'
        })
    },
    //获取列表
    getDataList: function (action, parameters, success, defeat, error) {
        $.ajax({
            url: CONFIG.HTTP + (CONFIG.VILLAGE_URLS[0][action] || CONFIG.GENERAL_IPS[0][action]),
            data: (function () {
                var data = {
                    menuId: tools.getUrlParam('menuId'),
                    pageIndex: 0,
                    pageSize: 10,
                    loginToken: LOGIN_TOKEN
                };
                console.log($.extend(data, parameters));
                return $.extend(data, parameters)
            })(),
            success: function (data) {
                console.log(data);
                if (data.status === 1) {
                    success && success(data)
                } else {
                    defeat && defeat(data)
                }
            },
            error: function (xhr, status, err) {
                error && error(status);
            },
            dataType: 'json'
        })
    },

    //获取列表ByID
    getDataById: function (action, id, success, defeat, error) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.VILLAGE_URLS[0][action],
            data: {
                objId: id,
                id: id,
                loginToken: LOGIN_TOKEN
            },
            success: function (data) {
                console.log(data);
                if (data.status === 1) {
                    success && success(data)
                } else {
                    defeat && defeat(data)
                }
            },
            error: function () {
                error && error();
            },
            dataType: 'json'
        })
    },
    //获取评论列表
    getCommentList: function (objId, pageIndex, pageSize, success, defeat, error) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.VILLAGE_URLS[0].culturaSouvenirServiceListV10,
            data: {
                objId: objId,
                pageIndex: pageIndex,
                pageSize: pageSize,
                loginToken: LOGIN_TOKEN
            },
            success: function (data) {
                console.log(data);
                if (data.status === 1) {
                    success && success(data)
                } else {
                    defeat && defeat(data)
                }
            },
            error: function () {
                error && error();
            },
            dataType: 'json'
        })
    },
    addComment: function (title, content, objId, success, defeat, error) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.VILLAGE_URLS[0].culturaSouvenirPraise,
            data: {
                title: title,
                content: content,
                objId: objId,
                loginToken: LOGIN_TOKEN
            },
            success: function (data) {
                console.log(data);
                if (data.status === 1) {
                    success && success(data)
                } else {
                    defeat && defeat(data)
                }
            },
            error: function () {
                error && error();
            },
            dataType: 'json'
        })
    },
    addReply: function (objId, content, userId, userName, success, defeat, error) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.VILLAGE_URLS[0].culturaReplyPraise,
            data: {
                content: content,
                objId: objId,
                userId: userId,
                userName: userName,
                loginToken: LOGIN_TOKEN
            },
            success: function (data) {
                console.log(data);
                if (data.status === 1) {
                    success && success(data)
                } else {
                    defeat && defeat(data)
                }
            },
            error: function () {
                error && error();
            },
            dataType: 'json'
        })
    },
    getReplyById: function (objId, success, defeat, error) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.VILLAGE_URLS[0].culturaSouvenirUserPraiseList,
            data: {
                objId: objId,
                loginToken: LOGIN_TOKEN
            },
            success: function (data) {
                console.log(data);
                if (data.status === 1) {
                    success && success(data)
                } else {
                    defeat && defeat(data)
                }
            },
            error: function () {
                error && error();
            },
            dataType: 'json'
        })
    },
    // 收藏
    addCollection: function (obj, resolve, reject) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.VILLAGE_URLS[0].addGovOpenCollectionV10,
            data: {
                objId: obj.id,
                objName: obj.name,
                loginToken: LOGIN_TOKEN
            },
            timeout: 10000,
            dataType: 'json',
            success: function (res) {
                if (res.status) {
                    resolve && resolve(res);
                } else {
                    reject && reject(res.msg || res.message);
                }
            },
            error: function (xhr, status, err) {
                if (status === 'timeout') {
                    reject && reject('请求超时，请稍后再试');
                } else {
                    reject && reject('请求出错，请稍后再试');
                }
            }
        });
    },

    // 取消收藏
    cancelCollection: function (ids, resolve, reject) {
        $.ajax({
            url: CONFIG.HTTP + CONFIG.VILLAGE_URLS[0].cancleGovOpenCollectionV10,
            data: {
                objIds: ids,
                loginToken: LOGIN_TOKEN
            },
            timeout: 10000,
            dataType: 'json',
            success: function (res) {
                if (res.status) {
                    resolve && resolve(res);
                } else {
                    reject && reject(res.msg || res.message);
                }
            },
            error: function (xhr, status, err) {
                if (status === 'timeout') {
                    reject && reject('请求超时，请稍后再试');
                } else {
                    reject && reject('请求出错，请稍后再试');
                }
            }
        });
    }
};

var tools = (function () {
    var obj = {
        getStore: function (name, toParse) {
            if (!name) return;
            try {
                var result = window.localStorage.getItem(name);
                result = toParse ? JSON.parse(result) : result;
                return result ? result : null;
            } catch (err) {
                console.log('此设备不支持localStorage!');
            }
        },

        setStore: function (name, value) {
            if (!name) return;
            try {
                value = value === undefined || typeof value === "function" ? value + '' : JSON.stringify(value);
                window.localStorage.setItem(name, value);
                return true;
            } catch (err) {
                console.log('此设备不支持localStorage!');
                return false;
            }
        },

        removeStore: function (name) {
            if (!name) return;
            try {
                window.localStorage.removeItem(name);
                return true;
            } catch (err) {
                console.log('此设备不支持localStorage!');
                return false;
            }
        },
        // 获取url参数
        getUrlParam: function (name) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
            var result = window.location.search.substring(1).match(reg);
            return result ? decodeURIComponent(result[2]) : null;
        },
        //跳转菜单
        HTMLEncode: function (html) {
            var temp = document.createElement("div");
            (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
            var output = temp.innerHTML;
            temp = null;
            return output;
        },
        HTMLDecode: function (text) {
            var temp = document.createElement("div");
            temp.innerHTML = text;
            var output = temp.innerText || temp.textContent;
            temp = null;
            return output;
        },
        SBEncode: function (content) {
            content = content.replace(/(&lt;br\/&gt;)|(\r\n)/gi, '</p><p>');
            content = '<p>' + content + '</p>';
            return content;
        },
        parseParam: function (param, key, encode) {
            if (param == null) return '';
            var paramStr = '';
            var t = typeof (param);
            if (t == 'string' || t == 'number' || t == 'boolean') {
                paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
            } else {
                for (var i in param) {
                    var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
                    paramStr += tools.parseParam(param[i], k, encode);
                }
            }
            return paramStr;
        },
        params: function (param) {
            return tools.parseParam(param).replace('&', '?');
        },
        hasClass: function (selector, cls) {
            return document.getElementById(selector).className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
        },
        addClass: function (selector, cls) {
            if (!this.hasClass(selector, cls)) document.getElementById(selector).className += " " + cls;
        },
        removeClass: function (selector, cls) {
            if (this.hasClass(selector, cls)) {
                var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
                document.getElementById(selector).className = document.getElementById(selector).className.replace(reg, ' ');
            }
        },
        toggleClass: function (selector, cls) {
            if (this.hasClass(selector, cls)) {
                this.removeClass(selectorobj, cls);
            } else {
                this.addClass(selector, cls);
            }
        },
        //日期格式化
        dateFormat: function (date, fmt) { //author: meizz
            var o = {
                "M+": date.getMonth() + 1, //月份
                "d+": date.getDate(), //日
                "h+": date.getHours(), //小时
                "m+": date.getMinutes(), //分
                "s+": date.getSeconds(), //秒
                "q+": Math.floor((date.getMonth() + 3) / 3), //季度
                "S": date.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        },
        //保存返回焦点
        saveFocus: function (data) {
            var active = document.getElementsByClassName('active');
            var leave = document.getElementsByClassName('leave');
            var active_save = [], leave_save = [];
            for (var i = 0; i < active.length; i++) {
                active_save.push(active[i].id)
            }
            for (var i = 0; i < leave.length; i++) {
                leave_save.push(leave[i].id)
            }
            var save = location.pathname.split('/')[location.pathname.split('/').length - 1];

            tools.setStore(save, {
                active_save: active_save,
                leave_save: leave_save,
                data: data
            })
        },
        getSave: function (key) {
            var save = location.pathname.split('/')[location.pathname.split('/').length - 1];
            var saveData = tools.getStore(save, true);

            if (saveData) {
                return saveData.data[key];
            } else {
                return '';
            }
        },
        getLeave: function () {
            var save = location.pathname.split('/')[location.pathname.split('/').length - 1];
            var saveData = tools.getStore(save, true);

            if (saveData) {
                return saveData.leave_save;
            } else {
                return '';
            }
        },
        //恢复返回焦点
        recoveryFocus: function () {
            var save = location.pathname.split('/')[location.pathname.split('/').length - 1];
            var curFocus = tools.getStore(save, true);
            if (curFocus) {
                tools.clearActive();
                for (var i = 0; i < curFocus.active_save.length; i++) {
                    tools.addClass(curFocus.active_save[i], 'active');
                    keyopt.options.focusElm = curFocus.active_save[i];
                }
                for (var i = 0; i < curFocus.leave_save.length; i++) {
                    tools.addClass(curFocus.leave_save[i], 'leave');
                }
                tools.removeStore(save);
            }
        },
        //清除active
        clearActive: function () {
            var items = document.getElementsByClassName('active');
            for (var i = 0; i < items.length; i++) {
                tools.removeClass(items[i].id, 'active')
            }
        },
        //清除leave
        clearLeave: function () {
            var items = document.getElementsByClassName('leave');
            for (var i = 0; i < items.length; i++) {
                tools.removeClass(items[i].id, 'leave')
            }
        },
        /**
         *
         * @param configUrl 配置项获取地址
         * @param loginToken 测试LOGIN_TOKEN 不传则需手动调用登陆接口
         */
        test: function (configUrl,loginToken) {
            $.ajax({
                url: configUrl,
                async: false,
                success: function (data) {
                    CONFIG = data;
                }
            });
            if (loginToken)
                LOGIN_TOKEN=loginToken;
        }
    };
    return obj;
})();

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
var log = {
    info: function (message) {
        if (DEBUG) {
            console.log(message)
        }
    },
    error: function (message) {
        if (DEBUG) {
            console.error(message)
        }
    },
    warn: function (message) {
        if (DEBUG) {
            console.warn(message)
        }
    }
};
var DEBUG = false;
var SERVER = '';
var BASE_URL = '';
var CONFIG_NAME = '';
var LOGIN_TOKEN_NAME = '';
var LOGIN_DATA_NAME = '';
var TEST_TOKEN = '';
var EXTEND = '';

var configFile='../config.json';
if (location.hostname==='localhost'){
    //开发环境使用config.dev.json作为配置获取
    configFile='../config.dev.json';
}
$.ajax({
    url: configFile,
    async: false,
    success: function (data) {
        SERVER = data.server;
        BASE_URL = data.baseUrl;
        CONFIG_NAME = data.configName;
        LOGIN_TOKEN_NAME = data.loginTokenName;
        LOGIN_DATA_NAME = data.loginDataName;
        TEST_TOKEN = data.testToken;
        EXTEND = data.extend;
    }
});

if (!tools.getStore(CONFIG_NAME, true)) {
    $.ajax({
        url: SERVER + BASE_URL,
        async: false,
        success: function (data) {
            tools.setStore(CONFIG_NAME, data);
        }
    });
}

var CONFIG = tools.getStore(CONFIG_NAME, true);
CONFIG.IP_CONFIG && (CONFIG.HTTP=CONFIG.IP_CONFIG);
var LOGIN_TOKEN = tools.getStore(LOGIN_TOKEN_NAME, true) || TEST_TOKEN;
var LOGIN_DATA = tools.getStore(LOGIN_DATA_NAME, true);
var USER_NAME = tools.getStore('user_name', true) || '未获取到昵称';


